package com.smart.redisson.controller;

import com.smart.redisson.aop.TestAnnotation;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@RestController
@Slf4j
public class DistributedLockController {
    private int quantity = 1000;
    @Resource
    RedissonClient redissonClient;
    /**
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/lock")
    public String lock() throws InterruptedException {
        RLock lock = redissonClient.getLock("lock:test");
//        lock.lock();
//        lock.lock(3, TimeUnit.SECONDS);
//        long waitTime, long leaseTime, TimeUnit unit
        //waitTime 获取锁的超时间
        //  long leaseTime  自动释放锁的时间
//        boolean isLock = lock.tryLock();
        boolean isLock = lock.tryLock(180, 3, TimeUnit.SECONDS);
        if (isLock) {
            try {
                quantity -= 1;
                log.info("数量:{}", quantity);
            } finally {
                lock.unlock();
            }
        }
        return "测试分布式锁";
    }

}
